package server

import (
	"errors"
	"fmt"
	"github.com/google/uuid"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"me/123/common/dao/mysql"
	"me/123/common/global"
	"me/123/common/model"
	"me/123/common/pkg"
	"me/123/common/proto/order"
)

func OrderCreate(req *order.OrderCreateRequest) (*order.OrderCreateResponse, error) {
	info, err := mysql.QueryProductInfo(req.ProductsId)
	if err != nil {
		return nil, err
	}

	if num := int64(info.Stock) - req.Num; num <= 0 {
		return nil, errors.New("库存不足")
	}

	orderSn := uuid.New().String()
	if req.CouponsId != 0 {
		coupons, err := mysql.QueryUserCouponsInfo(req.UserId, req.CouponsId)
		if err != nil {
			return nil, err
		}

		if coupons.UseMinPrice > info.Price*float64(req.Num) || coupons.CouponsStatus != 2 {
			return nil, errors.New("该优惠卷不可用")
		}

		o := model.Orders{
			Model:             gorm.Model{},
			UserId:            int32(req.UserId),
			OrderNumber:       orderSn,
			ProductsId:        int32(req.ProductsId),
			ProductsName:      info.StoreName,
			PayPrice:          info.Price*float64(req.Num) - coupons.CouponPrice,
			TotalPrice:        info.Price,
			PreferentialPrice: coupons.CouponPrice,
			Num:               int32(req.Num),
			OrderStatus:       3,
		}
		err = mysql.CreateOrder(&o)
		if err != nil {
			return nil, err
		}

		sprintf := fmt.Sprintf("%.2f", info.Price*float64(req.Num)-coupons.CouponPrice)
		alipay := pkg.NewAlipay()
		pay := alipay.Pay(info.StoreName, orderSn, sprintf)

		err = mysql.DestroyedCoupons(req.UserId, req.CouponsId, 3)
		if err != nil {
			zap.S().Error("核销优惠卷失败", zap.Error(err))
			return nil, err
		}

		return &order.OrderCreateResponse{Success: pay}, nil
	}

	o := model.Orders{
		Model:             gorm.Model{},
		UserId:            int32(req.UserId),
		OrderNumber:       orderSn,
		ProductsId:        int32(req.ProductsId),
		ProductsName:      info.StoreName,
		PayPrice:          info.Price * float64(req.Num),
		TotalPrice:        info.Price,
		PreferentialPrice: 0.00,
		Num:               int32(req.Num),
		OrderStatus:       3,
	}
	err = mysql.CreateOrder(&o)
	if err != nil {
		return nil, err
	}
	sprintf := fmt.Sprintf("%.2f", info.Price*float64(req.Num))
	alipay := pkg.NewAlipay()
	pay := alipay.Pay(info.StoreName, orderSn, sprintf)

	return &order.OrderCreateResponse{Success: pay}, nil
}

func UpdateOrderStatus(req *order.UpdateOrderStatusRequest) (*order.UpdateOrderStatusResponse, error) {
	info, err := mysql.QueryOrderInfo(req.OrderSn)
	if err != nil {
		return nil, err
	}
	p, err := mysql.QueryProductInfo(int64(info.ProductsId))
	if err != nil {
		return nil, err
	}

	uid, err := mysql.QueryUserInfoByUid(int64(info.UserId))
	if err != nil {
		return nil, err
	}

	tx := global.DB.Begin()

	err = mysql.UpdateOrderStatus(req.OrderSn, req.OrderStatus, tx)
	if err != nil {
		tx.Rollback()
		zap.S().Error("修改订单状态失败:", zap.Error(err))
		return nil, err
	}

	stock := int32(p.Stock) - info.Num
	err = mysql.UpdateProductStock(info.ProductsId, stock, tx)
	if err != nil {
		tx.Rollback()
		zap.S().Error("扣减库存失败:", zap.Error(err))
		return nil, err
	}

	Integral := uid.Integral + info.PayPrice
	err = mysql.UserIntegral(int64(info.UserId), Integral, tx)
	if err != nil {
		tx.Rollback()
		zap.S().Error("获取积分失败:", zap.Error(err))
		return nil, err
	}

	tx.Commit()

	return &order.UpdateOrderStatusResponse{}, nil
}
